import BaseService from "./BaseService";
import dbHelper from '../utils/better-db-helper';

class CustomerService extends BaseService{
  emptyData = {
    customerName: "",
    addr: "",
    contact: "",
    gender: "",
    duty: "",
    cellphone: ""
  }

  getById(id) {
    return dbHelper.getById(`select * from customer where id=@id`, {id});
  }
  list(params) {
    const {
      pageNumber,
      pageSize,
      customerName,
      addr,
      contact,
      gender,
      cellphone
    } = Object.assign({}, this.emptyData, this.pagination, params);

    const whereSegment = `where customer_name like @customerName and
     cellphone like @cellphone and gender like @gender
     and contact like @contact and addr like @addr`;

    const sqlParams = {
      customerName: `%${customerName}%`,
      addr: `%${addr}%`,
      cellphone: `%${cellphone}%`,
      contact: `%${contact}%`,
      gender: `%${gender}%`
    };

    //total
    const total = dbHelper.count(`select count(*) from customer ${whereSegment}`, sqlParams);
    //rows
    const rows = dbHelper.queryRows(`select 
      id, customer_name customerName,
      cellphone,addr,
      gender,duty,contact
      from customer ${whereSegment} limit @offset, @limit`,
    Object.assign(sqlParams, {
      offset: (pageNumber - 1) * pageSize,
      limit: pageSize
    }));
    return {
      rows,
      total
    };
  }

  add(params) {
    return dbHelper.insert("insert into customer values(null, @customerName, @addr, @contact,@gender, @duty, @cellphone)", Object.assign({}, this.emptyData, params));
  }

  update(id, params) {
    return dbHelper.update("update customer set customer_name=@customerName, addr=@addr, contact=@contact, gender=@gender, duty=@duty,cellphone=@cellphone where id =@id", Object.assign({
      id
    }, this.emptyData, params));
  }

  delete(id) {
    return dbHelper.delete("delete from customer where id = @id", {
      id
    });
  }
}
export default new CustomerService;
